package sicnu.cs.ich.security.security.service;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import sicnu.cs.ich.security.domain.entity.Permission;
import sicnu.cs.ich.security.domain.entity.Role;
import sicnu.cs.ich.security.domain.entity.User;
import sicnu.cs.ich.security.mapper.PermissionMapper;
import sicnu.cs.ich.security.mapper.UserMapper;

import java.util.HashSet;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class  UserDetailServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 校验账号
        // 邮箱登录
        String emailChar = "@";
        User user;
        if (username.contains(emailChar)) {
            user = userMapper
                    .findOptionalByEmail(username)
                    .orElseThrow(() -> new UsernameNotFoundException("Cannot find email"));
        }// 账号/手机登录
        else {
            user = userMapper
                    .findOptionalByUsername(username)
                    .orElseThrow(() -> new UsernameNotFoundException("Cannot find username"));
        }
        if(!CollectionUtils.isEmpty(user.getRoles())){
            var permissions = permissionMapper.findPermissionsByRoles(
                    user.getRoles().stream().map(Role::getId).collect(Collectors.toList()));
            user.setAuthorities(permissions);
        }else throw new UsernameNotFoundException("用户无角色");
        return user;
    }
}




